package version3.part2.Server.provider;

import version3.part2.Server.serviceRegister.ServiceRegister;
import version3.part2.Server.serviceRegister.impl.ZKServiceRegister;

import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.Map;


public class ServiceProvider {
    private Map<String,Object> interfaceProvider;
    private String host;
    private int port;
    private ServiceRegister serviceRegister;

    public ServiceProvider(String host, int port) {
        this.host = host;
        this.port = port;
        this.interfaceProvider=new HashMap<>();
        this.serviceRegister=new ZKServiceRegister();
    }

    public void provideServiceInterface(Object service,boolean isRetry){
        Class<?>[] interfaceName=service.getClass().getInterfaces();

        for (Class<?> clazz:interfaceName){
            // 本地映射 服务名(接口) -> 服务对象
            interfaceProvider.put(clazz.getName(),service);
            // Zookeeper 映射 服务名(接口) -> 服务地址
            serviceRegister.register(clazz.getName(),new InetSocketAddress(host,port),isRetry);
        }


    }

    public Object getService(String interfaceName){
        return interfaceProvider.get(interfaceName);
    }

}
